package project.pojo;

import java.math.BigDecimal;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @author d11yu
 */
public class Cart {
//    private Integer count;
//    private BigDecimal totalPrice;
    private Map<Integer, CartItem> items = new LinkedHashMap<>();

    //region constructors
    public Cart() {
    }

    //endregion

    //region getters and setters
    public Integer getCount() {
        Integer count = 0;
        for (CartItem item : this.items.values()) {
            count += item.getCount();
        }
        return count;
    }

    public BigDecimal getTotalPrice() {
        BigDecimal totalPrice = new BigDecimal(0);
        for (CartItem item : this.items.values()) {
            totalPrice = totalPrice.add(item.getTotalPrice());
        }
        return totalPrice;
    }

    public Map<Integer, CartItem> getItems() {
        return items;
    }

    public void setItems(Map<Integer, CartItem> items) {
        this.items = items;
    }
    //endregion

    @Override
    public String toString() {
        return "Cart{" +
                "count=" + this.getCount() +
                ", totalPrice=" + this.getTotalPrice() +
                ", items=" + this.getItems() +
                '}';
    }

    public void addItem(CartItem cartItem) {
        CartItem item = this.items.get(cartItem.getId());
        if (item == null) {
            this.items.put(cartItem.getId(), cartItem);
        } else {
            item.setCount(item.getCount() + 1);
            item.setTotalPrice(item.getTotalPrice().add(cartItem.getPrice()));
        }
    }

    /**
     * 根据指定id删除cartItem
     *
     * @param id
     */
    public void deleteItem(Integer id) {
        CartItem cartItem = this.items.get(id);
        if (cartItem != null) {
            this.items.remove(id);
        }
    }

    /**
     * 清空购物车
     */
    public void clear() {
        this.items.clear();
    }

    public void updateCount(Integer id, Integer count) {
        CartItem item = this.items.get(id);
        if (item != null) {
            // old item total price
            BigDecimal oitp = item.getTotalPrice();
            // old item count
            Integer oic = item.getCount();
            item.setCount(count);
            item.setTotalPrice(item.getPrice().multiply(BigDecimal.valueOf(count)));
        }
    }
}
